package holdtime.xlxc.activities.practicedriving;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import holdtime.xlxc.R;
import holdtime.xlxc.model.QueryAddress;
import holdtime.xlxc.tools.util.ActionBarUtil;
import holdtime.xlxc.tools.util.ImageUtil;
import holdtime.xlxc.tools.util.SharedPreferencesUtil;
import holdtime.xlxc.tools.util.ToastUtil;
import holdtime.xlxc.tools.zxing.config.ZXingLibConfig;
import holdtime.xlxc.tools.zxing.integrator.IntentIntegrator;
import holdtime.xlxc.tools.zxing.integrator.IntentResult;

public class PracticeDrivingMenuActivity extends ActionBarUtil {

    private static int CAMERA_CODE = 11;
    Button beginBtn;//开始、结束按钮
    ImageView banner;
    ListView listView;
    Button sc;
    Button mnq;
    Button menutwo;
    Button menuthree;
    String[] menuForIndexTwo = {"基础驾驶", "场地驾驶", "第二部分综合驾驶及考核"};
    String[] menuForIndexThree = {"跟车行驶", "变更车道", "靠边停车", "掉头", "通过路口", "通过人行横道", "通过学校区域", "通过公共汽车站", "会车", "超车", "夜间驾驶", "恶劣条件下的驾驶", "山区道路驾驶", "高速公路驾驶", "行驶路线选择", "第三部分综合驾驶及考核"};
    private ZXingLibConfig zxingLibConfig;
    private MenuAdapter adapter;
    private String stuId = "";
    private String stuName = "";
    private String stuNum = "";
    private String kcfsCode = "";//课程方式
    private String pxbfCode = "";//培训部分
    private String pxcxCode = "";//培训车型
    private String pxxmCode = "";//培训项目
    private String kcbmCode = "";//课程编码：上面四个加起来
    private String pxxm = "";//培训项目
    private boolean isChooseMenuThree = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setActionBarTitle("练车选项");
        this.setHomeAsUpEnabled(true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_practice_driving_menu);

        beginBtn = (Button) findViewById(R.id.begin);
        banner = (ImageView) findViewById(R.id.banner);
        listView = (ListView) findViewById(R.id.jslc_lv);
        sc = (Button) findViewById(R.id.sc);
        mnq = (Button) findViewById(R.id.mnq);
        menutwo = (Button) findViewById(R.id.menutwo);
        menuthree = (Button) findViewById(R.id.menuthree);

        banner.setImageBitmap(ImageUtil.streamBitmap(this, R.drawable.counttime_banner));

        //获取学员信息
        QueryAddress address = new QueryAddress();
        String url = address.studentInfo((String) SharedPreferencesUtil.get(this, "add", ""), (String) SharedPreferencesUtil.get(this, "num", ""));
        queryStudentInfo(url);

        zxingLibConfig = new ZXingLibConfig();
        zxingLibConfig.useFrontLight = true;

        beginBtn.setEnabled(false);
        beginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scan();
            }
        });

//        adapter = new MenuAdapter(this, menuForIndexThree);
//        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                adapter.setSelectedIndex(i);
                if (!isChooseMenuThree) {
                    pxxmCode = String.valueOf(i + 11);
                    pxxm = menuForIndexTwo[i];
                } else {
                    pxxmCode = String.valueOf(i + 21);
                    pxxm = menuForIndexThree[i];
                }
            }
        });

        sc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sc.setBackgroundResource(R.drawable.orange_bk);
                mnq.setBackgroundResource(R.drawable.border_jslc_table);
                sc.setTextColor(Color.WHITE);
                mnq.setTextColor(Color.BLACK);
                kcfsCode = "1";
            }
        });

        mnq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mnq.setBackgroundResource(R.drawable.orange_bk);
                sc.setBackgroundResource(R.drawable.border_jslc_table);
                mnq.setTextColor(Color.WHITE);
                sc.setTextColor(Color.BLACK);
                kcfsCode = "3";
            }
        });

        menutwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isChooseMenuThree = false;
                menutwo.setBackgroundResource(R.drawable.orange_bk);
                menuthree.setBackgroundResource(R.drawable.border_jslc_table);
                menutwo.setTextColor(Color.WHITE);
                menuthree.setTextColor(Color.BLACK);
                adapter = null;
                adapter = new MenuAdapter(PracticeDrivingMenuActivity.this, menuForIndexTwo);
                listView.setAdapter(adapter);
                pxxmCode = "";
                pxbfCode = "2";
            }
        });

        menuthree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isChooseMenuThree = true;
                menuthree.setBackgroundResource(R.drawable.orange_bk);
                menutwo.setBackgroundResource(R.drawable.border_jslc_table);
                menuthree.setTextColor(Color.WHITE);
                menutwo.setTextColor(Color.BLACK);
                adapter = null;
                adapter = new MenuAdapter(PracticeDrivingMenuActivity.this, menuForIndexThree);
                listView.setAdapter(adapter);
                pxxmCode = "";
                pxbfCode = "3";
            }
        });
    }

    private void queryStudentInfo(String url) {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
//                            String result = response.substring(1, response.length() - 1).replace("\\", "");
                            JSONObject jo = new JSONObject(response);
                            String resultCode = jo.getString("resultCode");
                            if (resultCode.equals("0")) {//是学员
                                stuId = jo.getJSONObject("record").getString("stunum");
                                stuName = jo.getJSONObject("record").getString("name");
                                stuNum = jo.getJSONObject("record").getString("personNum");
//                                classId = jo.getJSONObject("Record").getString("learnTime");
                                String cartype = jo.getJSONObject("record").getString("cartype");
                                queryCarTypeCode(cartype);
                                beginBtn.setEnabled(true);
                            } else {
                                ToastUtil.showToast(getBaseContext(), "非学员不能练车");
                                finish();
                            }
                        } catch (JSONException e) {
                            ToastUtil.showToast(getBaseContext(), "加载失败");
                            finish();
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ToastUtil.showToast(getBaseContext(), "加载失败");
                finish();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(getResources().getInteger(R.integer.defaultRequestTimeOut), DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(stringRequest);
    }

    private void queryCarTypeCode(String carType) {
        switch (carType) {
            case "无":
                pxcxCode = "00";
                break;
            case "A1":
                pxcxCode = "01";
                break;
            case "A2":
                pxcxCode = "02";
                break;
            case "A3":
                pxcxCode = "03";
                break;
            case "B1":
                pxcxCode = "11";
                break;
            case "B2":
                pxcxCode = "12";
                break;
            case "C1":
                pxcxCode = "21";
                break;
            case "C2":
                pxcxCode = "22";
                break;
            case "C3":
                pxcxCode = "23";
                break;
            case "C4":
                pxcxCode = "24";
                break;
            case "C5":
                pxcxCode = "25";
                break;
            case "D":
                pxcxCode = "31";
                break;
            case "E":
                pxcxCode = "32";
                break;
            case "F":
                pxcxCode = "33";
                break;
            case "M":
                pxcxCode = "41";
                break;
            case "N":
                pxcxCode = "42";
                break;
            case "P":
                pxcxCode = "43";
                break;
            default:
                break;
        }
    }

    private void scan() {
        if (kcfsCode.equals("")) {
            ToastUtil.showToast(getBaseContext(), "请选择课程方式");
        } else if (pxbfCode.equals("")) {
            ToastUtil.showToast(getBaseContext(), "请选择培训部分");
        } else if (pxxmCode.equals("")) {
            ToastUtil.showToast(getBaseContext(), "请选择培训项目");
        } else if (pxcxCode.equals("")) {
            ToastUtil.showToast(getBaseContext(), "培训车型获取异常");
        } else {
//            kcbmCode = kcfsCode + pxcxCode + pxbfCode + pxxmCode + String.valueOf((int)(Math.random() * 9000 + 1000));
            kcbmCode = kcfsCode + pxcxCode + pxbfCode + pxxmCode + "0000";
            if (ActivityCompat.checkSelfPermission(PracticeDrivingMenuActivity.this, Manifest.permission.CAMERA)//6.0相机权限
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(PracticeDrivingMenuActivity.this, new String[]{Manifest.permission.CAMERA}, CAMERA_CODE);
            } else {
                IntentIntegrator.initiateScan(PracticeDrivingMenuActivity.this, zxingLibConfig);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case IntentIntegrator.REQUEST_CODE:
                IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode,
                        resultCode, data);
                if (scanResult == null) {
                    return;
                }
                final String result = scanResult.getContents();
                if (result != null) {
                    handleResult(result);
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void handleResult(String resultString) {
        if (!resultString.equals("")) {
            if (resultString.startsWith("start") && resultString.endsWith("end")) {
                Intent resultIntent = new Intent(this, PracticeDrivingActivity.class);
                resultIntent.putExtra("result", resultString);
                resultIntent.putExtra("stuId", stuId);
                resultIntent.putExtra("stuName", stuName);
                resultIntent.putExtra("stuNum", stuNum);
                long currentTimeMillis = System.currentTimeMillis() / 1000;
                String classId = String.valueOf(currentTimeMillis);
                resultIntent.putExtra("classId", classId);
                resultIntent.putExtra("kcbmCode", kcbmCode);
                resultIntent.putExtra("pxxm", pxxm);
                resultIntent.putExtra("pxbfCode", pxbfCode);
                startActivity(resultIntent);
                finish();
            } else {
                ToastUtil.showToast(this, "非计时终端二维码\n" + resultString);
            }
        }
    }
` `
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == CAMERA_CODE) {
            IntentIntegrator.initiateScan(PracticeDrivingMenuActivity.this, zxingLibConfig);
        }
    }

    public class MenuAdapter extends BaseAdapter {
        private Context context;
        private String[] testList;
        private int selectedIndex;

        MenuAdapter(Context ctx, String[] testList) {
            this.context = ctx;
            this.testList = testList;
            selectedIndex = -1;
        }

        private void setSelectedIndex(int ind) {
            selectedIndex = ind;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return testList.length;
        }

        @Override
        public Object getItem(int position) {
            return testList[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View vi = convertView;
            ViewHolder holder;
            if (convertView == null) {
                vi = LayoutInflater.from(context).inflate(R.layout.layout_jslc_listview, null);
                holder = new ViewHolder();
                holder.tv = (TextView) vi.findViewById(R.id.jslc_tv);
                vi.setTag(holder);
            } else {
                holder = (ViewHolder) vi.getTag();
            }
            if (selectedIndex != -1 && position == selectedIndex) {//选中
                holder.tv.setBackgroundResource(R.drawable.orange_bk);
                holder.tv.setTextColor(Color.WHITE);
            } else {//默认
                holder.tv.setBackgroundResource(R.drawable.border_jslc_table);
                holder.tv.setTextColor(Color.BLACK);
            }
            holder.tv.setText(testList[position]);
            holder.tv.setPadding(30, 0, 0, 0);
            return vi;
        }

        private class ViewHolder {
            TextView tv;
        }
    }
}
